<?php

App::uses('Security', 'Utility');

class AuthusergroupsController extends AppController {

    var $helpers = array('Html', 'Form');
    var $uses = array('Authusergroup', 'Authresourcegroup', 'Authresource', 'Authpermission');
    var $paginate = array('limit' => '10');

    function index() {
        $this->set('menu', 'users');
        $this->set('submenu', 'usergroups');
        $this->set('cakeDescription', 'User Groups');
        $this->set('title_for_layout', 'Index');
        $textsearch = "";
        if (!empty($this->data)) {
            $textsearch = $this->data['Authusergroup']['textsearch'];
            $this->paginate['conditions'] = array('Authusergroup.name LIKE' => '%' . $textsearch . '%');
        } else {
            if (isset($this->params['named']['textsearch'])) {
                $textsearch = $this->params['named']['textsearch'];
                $this->paginate['conditions'] = array('Authusergroup.name LIKE' => '%' . $textsearch . '%');
            }
        }
        $this->Authusergroup->recursive = 0;
        $this->set('authusergroups', $this->paginate());
        $this->set('textsearch', $textsearch);
    }

    function view($id = null) {
        $this->set('menu', 'users');
        $this->set('submenu', 'usergroups');
        $this->set('cakeDescription', 'User Groups');
        $this->set('title_for_layout', 'View');
        if (!$id) {
            $this->Session->setFlash(__('Invalid Authusergroup', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Authusergroup->recursive = 1;
        $arr_usergroup = $this->Authusergroup->find('first', array('conditions' => array('Authusergroup.id' => $id)));
        $parent_id = $arr_usergroup['Authusergroup']['parent_id'];
        $arr_parentgroup = $this->Authusergroup->find('first', array('conditions' => array('Authusergroup.id' => $parent_id)));
        $this->set('authusergroup', $arr_usergroup);
        $this->set('parentgroup', $arr_parentgroup);
    }

    function add() {
        $this->set('menu', 'users');
        $this->set('submenu', 'usergroups');
        $this->set('cakeDescription', 'User Groups');
        $this->set('title_for_layout', 'Add');
        if (!empty($this->data)) {
            $this->Authusergroup->create();
            if ($this->Authusergroup->save($this->data)) {
                $group_id = $this->Authusergroup->getLastInsertId();
                if (array_key_exists('newPermissions', $this->data)) {
                    foreach ($this->data['newPermissions'] as $permission) {
                        if (array_key_exists('checkbox', $permission)) {
                            $item_id = $permission['checkbox'];
                            $allow = (array_key_exists('allow', $permission)) ? $permission['allow'] : 0;
                            $arrData = array('authresource_id' => $item_id, 'authusergroup_id' => $group_id, 'allow' => $allow);
                            $this->Authpermission->create();
                            $this->Authpermission->save($arrData);
                        }
                    }
                }
                $this->Session->setFlash(__('The Authusergroup has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Authusergroup could not be saved. Please, try again.', true));
            }
        }
        $authresources = $this->Authusergroup->Authresource->find('list');
        $parentusergroups = $this->Authusergroup->Parentusergroup->find('list');
        $tree = $this->__gettree();
        $this->set(compact('authresources', 'parentusergroups', 'tree'));
    }

    function edit($id = null) {
        $this->set('menu', 'users');
        $this->set('submenu', 'usergroups');
        $this->set('cakeDescription', 'User Groups');
        $this->set('title_for_layout', 'Edit');
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid Authusergroup', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if (empty($this->data['Authusergroup']['parent_id'])) {
                $this->data['Authusergroup']['parent_id'] = 'EMPTY';
            }
            if ($this->Authusergroup->save($this->data)) {
                $group_id = $this->data['Authusergroup']['id'];
                $this->Authpermission->deleteAll(array('Authpermission.authusergroup_id' => $group_id));
                if (array_key_exists('newPermissions', $this->data)) {
                    foreach ($this->data['newPermissions'] as $permission) {
                        if (array_key_exists('checkbox', $permission)) {
                            $item_id = $permission['checkbox'];
                            $allow = (array_key_exists('allow', $permission)) ? $permission['allow'] : 0;
                            $arrData = array('authresource_id' => $item_id, 'authusergroup_id' => $group_id, 'allow' => $allow);
                            $this->Authpermission->create();
                            $this->Authpermission->save($arrData);
                        }
                    }
                }
                $this->Session->setFlash(__('The Authusergroup has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The Authusergroup could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Authusergroup->read(null, $id);
        }
        $authresources = $this->Authusergroup->Authresource->find('list');
        $parentusergroups = $this->Authusergroup->Parentusergroup->find('list');
        $tree = $this->__gettree($id, 0);
        $this->set(compact('authresources', 'parentusergroups', 'tree'));
    }

    function delete($id = null) {
        Configure::write('debug', 0);
        if (!$id) {
            $this->Session->setFlash(__('Invalid Authusergroup', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Authusergroup->delete($id)) {
            $this->Authusergroup->recursive = -1;
            $arrUsergroups = $this->Authusergroup->find('all', array('conditions' => array('parent_id' => $id)));
            if (count($arrUsergroups) > 0) {
                $arr_data = array();
                foreach ($arrUsergroups as $data) {
                    $arr_data = array('id' => $data['Authusergroup']['id'], 'parent_id' => 'EMPTY');
                    $this->Authusergroup->save($arr_data);
                }
            }
            $this->Session->setFlash(__('Authusergroup deleted', true));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('not deleted', true));
            $this->redirect(array('action' => 'index'));
        }
    }

    /*======================================  private  functions ===================================================================*/

	
	function __gettree($authusergroup_id = null, $allow = true, $name = "newPermissions")
	{
		$this->Authresourcegroup->recursive =-1;
		$main_group = $this->Authresourcegroup->find('first', array('conditions' => array('parent_id' => 'EMPTY')));
		//pr($main_group);
		
		$checkedItems = array();
                $arrCurrItems = array();// contendra la lista de los user_id permitidos para este grupo
		if($authusergroup_id){
		$this->Authpermission->recursive =-1;
		$checkedItems = $this->Authpermission->find('all', array('conditions' => array('Authusergroup_id' =>$authusergroup_id)));
                //pr($checkedItems);

                if(count($checkedItems) > 0){
                    foreach($checkedItems as $data){
                        $aNew = array($data['Authpermission']['authresource_id'] => $data['Authpermission']['allow']);
                        $arrCurrItems = array_merge($arrCurrItems,$aNew);
                    }
                }



		}
		
		$text = "";
		$text.= "<ul class=\"tree\"><li>";
		$text.= "<input type=\"checkbox\"><label class='nodo'>".$main_group['Authresourcegroup']['name']."</label>";
		$text.= $this->__recursivetree($main_group['Authresourcegroup']['id'], $name, $arrCurrItems, $allow);
		$text.= "</li></ul>";
		return $text;
	}
	

    function __recursivetree($cur_parent, $name, $arrCurrItems ,$allow, $text="")
    {
	   $this->Authresource->recursive = -1;
	   $this->Authresourcegroup->recursive = -1;
	   $arrGroups = $this->Authresourcegroup->find('all', array('conditions' => array('Authresourcegroup.parent_id' => $cur_parent)));
           
        if(!empty($arrGroups))
        {
			$text= "<ul>";
			foreach($arrGroups  as $data)
                        {
                            $text.= "<li>";
                            $text.= "<input type='checkbox'  name='".$data['Authresourcegroup']['id']."' id='".$data['Authresourcegroup']['id']."'value='1'>";
                            $text.= "<label class='nodo'>".$data['Authresourcegroup']['name']."</label>";
                            $text.= $this->__recursivetree($data['Authresourcegroup']['id'], $name ,$arrCurrItems, $allow );
                            $text.= "</li>";
			}
			$text.= "</ul>";
			
        }
        else{
            $arrItems= $this->Authresource->find('all', array('conditions' => array('Authresource.authresourcegroup_id' => $cur_parent ),'order'=>array('Authresource.description')));
            
            if(count($arrItems) > 0 ){
				$text= "<ul>";                            
				foreach($arrItems as $dataleaf){
 					 // buscar si el id $data['User']['id'] en el array checkedUsers
					 // si lo encuentro el id pongo checked a este 
					// pr($arrCurrItems);
					 $checked = "";
					 $checked_1 = "checked";
					 $checked_0 = "";
					/* foreach($arrCurrItems as $currItem){
						if(in_array($dataleaf['Ngauthresource']['id'], $currItem)){
							$checked = "checked";	
							if(in_array(1,$currItem)){
								$checked_1 = "checked";
								$checked_0 = "";
							}
							else{
								$checked_1 = "";
								$checked_0 = "checked";
							}
						 }
					 }*/

                                         $resource_id = $dataleaf['Authresource']['id'];
                                         if(array_key_exists($resource_id, $arrCurrItems)){
                                                $checked = "checked";
                                                if($arrCurrItems[$resource_id] == '1'){
                                                        $checked_1 = "checked";
                                                        $checked_0 = "";
                                                }
                                                else{
                                                        $checked_1 = "";
                                                        $checked_0 = "checked";
                                                }
                                         }
					 
					 
					 $ckeckname = "data[".$name."][".$dataleaf['Authresource']['id']."][checkbox]";
					 $checkvalue = $dataleaf['Authresource']['id'];
					 $radioallow = "data[".$name."][".$dataleaf['Authresource']['id']."][allow]";
					 
					 $text.= "<li>";
                                         $text.= "<input type='checkbox'  name='".$ckeckname."' ";
                                         $text.= "id='".$dataleaf['Authresource']['id']."' value='".$checkvalue."' ".$checked.">";
					 
					 $resourcename = $dataleaf['Authresource']['name'];
					 if(strlen($dataleaf['Authresource']['description']) > 0)
					 $resourcename = $dataleaf['Authresource']['description'];
					 /*
					 $text.= "<label class='hoja'>".$resourcename."</label>";
					 $text.= "<label>&nbsp;(Permitir&nbsp;</label>";
					 
					 if($allow){
					 $text.= "<label><input type='radio' name='".$radioallow."' value='1' checked id='Permitir_1' />&nbsp;Sí&nbsp;</label>";
					 $text.= "<label><input type='radio' name='".$radioallow."' value='0' id='Permitir_0' />&nbsp;No&nbsp;</label>";
					 }
					 else{
					 $text.= "<label><input type='radio' name='".$radioallow."' value='1' ".$checked_1." id='Permitir_1' />&nbsp;Sí&nbsp;</label>";
					 $text.= "<label><input type='radio' name='".$radioallow."' value='0' ".$checked_0." id='Permitir_0' />&nbsp;No&nbsp;</label>";
					 }
					 $text.= ")";
                                         */
                                         $text.= "<label class='hoja'>Permitir: ".$resourcename."</label>";
					 $text.= "<label>&nbsp;(</label>";

					 if($allow){
					 $text.= "<label><input type='radio' name='".$radioallow."' value='1' checked id='Permitir_1' />&nbsp;Sí&nbsp;</label>";
					 $text.= "<label><input type='radio' name='".$radioallow."' value='0' id='Permitir_0' />&nbsp;No&nbsp;)</label>";
					 }
					 else{
					 $text.= "<label><input type='radio' name='".$radioallow."' value='1' ".$checked_1." id='Permitir_1' />&nbsp;Sí&nbsp;</label>";
					 $text.= "<label><input type='radio' name='".$radioallow."' value='0' ".$checked_0." id='Permitir_0' />&nbsp;No&nbsp;)</label>";
					 }
					 //$text.= "";
					 
                     $text.= "</li>";
                }
                 $text.= "</ul>";
                
			}
               
        }
		return $text;

    }
}
?>